package com.decent.common.util.http;

import com.decent.common.entity.http.ParamNode;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;

import java.util.Comparator;
import java.util.List;

/**
 * @author: decent Gjh
 * @date: 2022/10/28/17:30
 * @description:
 */
public class ChengHttpUtils {

    /**
     * 橙券接口请求工具
     * @param url 资源路径 例如：/coupon/goods/stock
     * @param params 参数 通过list<ParamNode<>>方式传递 无需包含时间戳
     * @param key key值
     * @return json字符串
     */
    public static String getUrl(String url, List<ParamNode<String,Object>> params,String key){
        WebClient client = WebClient.create();
        params.sort(Comparator.comparing(ParamNode::getKey));
        StringBuilder sign = new StringBuilder();

        for (ParamNode<String,Object> node:params) {
            sign.append(node);
            sign.append("&");
        }
        String param = sign.toString();
        sign.append("key=").append(key);
        String s = DigestUtils.md5DigestAsHex(sign.toString().getBytes()).toUpperCase();
        Flux<String> flux = client.get().uri("http://192.168.60.177:4321"+url+"?" + param + "&sign=" + s)
                .retrieve()
                .bodyToFlux(String.class);
        return flux.blockFirst();
    }
}
